<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :http-request="handleUpload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :before-remove="beforeRemove"
    :before-upload="beforeUpload"
    :show-file-list="false">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { getFileNameUUID, put, signatureUrl } from '@/plugin/oss/ali-oss'

export default {
  components: {},

  data () {
    return {
      imageUrl: ''
    }
  },

  methods: {
    handleRemove (file, fileList) {
      this.$emit('on-remove', file, fileList)
    },
    handlePreview (file) {
      this.$emit('on-preview', file)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess (response, file, fileList) {
      this.fileList = fileList
      this.$emit('on-success', file, fileList)
    },
    beforeUpload (file) {
      // 限制上传类型
      // const fileExtensions = getFileNameUUID(file.name) === '.png' || getFileNameUUID(file.name) === '.docx' || getFileNameUUID(file.name) === '.pdf'
      // 限制的上限为20M
      const max20M = file.size / 1024 / 1024 < 20
      // if (!fileExtensions) {
      //   this.$message.error('上传文件类型只能是 .doc, .docx, .pdf 格式!')
      // }
      if (!max20M) {
        this.$message.error('上传文件大小不能超过 20MB!')
      }
      // return fileExtensions && max20M
      return max20M
    },
    /**
     * 自定义上传方法
     */
    handleUpload (option) {
      // 获取文件的后缀名
      let objName = getFileNameUUID()
      let obj = option.file.name
      const index = obj.lastIndexOf('.')
      obj = obj.substring(index, obj.length)
      // 生成的文件名，保留文件后缀名，进行拼接
      objName = getFileNameUUID() + getFileNameUUID(option.file.name)

      // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
      put(`flieName/${objName}`, option.file).then(res => {
        console.log(res)
        // 上传成功之后，转换真实的地址
        signatureUrl(`flieName/${objName}`).then(res => {
          this.imageUrl = res
        })
      })
    }
  }
}
</script>

<style >
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
